#include <cstdlib>
#include <hacks/base/hacks_conf.h>
#include <hacks/base/ev_utils.h>

void timer_cb(const hacks::shared_ev_timer &timer) {
    printf("timer_cb called !!\r\n");
    timer->stop_timer();
}

void ext_timer_cb(hacks::ev_timer &timer, const hacks::shared_ev_async &async) {
    static std::size_t num = 0;
    printf("ext_timer_cb called n = %lu !!\r\n", ++num);
    if (num == 20) {
        timer.stop_timer();
        async->stop_async_task();
    } else {
        async->active();
        timer.restart_timer();
    }
}

void timer_close_cb(hacks::ev_timer &timer) {
    printf("timer closed !!\r\n");
    auto evl = timer.get_event_loop();
    evl->stop_loop();
}

void async_cb(hacks::ev_async &async_ins) {
    printf("async cb called!\r\n");
    //async_ins->stop_async_task();
}

void async_close_cb(hacks::ev_async &async_ins) {
    printf("async close cb called!\r\n");
}

int main(int argc, char **argv) {
    hacks::shared_ev_loop loop = hacks::mk_ev_loop();

    hacks::ev_os_fd_t hd = STDIN_FILENO;
    auto filefd = hacks::mk_ev_file_fd(loop,
                                       hd,
                                       [](hacks::ev_file_fd &ins, int status, int evt) {
                                           auto fd_hd = ins.get_os_fd();

                                       });

    /* build async and commit */
    auto async = hacks::mk_ev_async(
            loop,
            std::bind(&async_cb, std::placeholders::_1),
            std::bind(&async_close_cb, std::placeholders::_1));
    async->commit();
    /* */

    /* build timer and commit */
    auto timer = hacks::mk_ev_timer(
            loop,
            std::bind(&ext_timer_cb, std::placeholders::_1, async),
            std::bind(&timer_close_cb, std::placeholders::_1),
            100, 0);
    timer->commit();
    /* */

    /* try active async*/
    async->active();

    loop->run_loop();

    return EXIT_SUCCESS;
}
